package com.erb.config;

import com.erb.constants.RabbitMqConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class RabbitMqConfig {

	public static final Logger logger = LoggerFactory.getLogger(RabbitMqConfig.class);

	@Autowired
	CachingConnectionFactory cachingConnectionFactory;

	@Bean
	public RabbitTemplate rabbitTemplate() {
		RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
		rabbitTemplate.setConfirmCallback((data, ack, cause) -> {
			String id = data.getId();
			if (ack) {
				logger.info(id + " 发送成功");
			} else {
				logger.info(id + " 发送失败");
			}
		});
		rabbitTemplate.setReturnCallback((message, i, s, s1, s2) -> {
			logger.info("发送失败");
		});
		return rabbitTemplate;
	}

	@Bean
	public Queue createQueue() {
		return new Queue(RabbitMqConstants.ERB_QUEUE_NAME);
	}

	@Bean
	public DirectExchange createExchange() {
		return new DirectExchange(RabbitMqConstants.ERB_EXCHANGE_NAME, true, false);
	}

	@Bean
	public Binding binding() {
		return BindingBuilder.bind(createQueue()).to(createExchange()).with(RabbitMqConstants.ERB_KEY_NAME);
	}

}
